package com.sgb.kjwl.view.ui.fragment.transport;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.amap.api.maps.model.LatLng;
import com.swgk.core.util.LogUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentGoodsListBinding;
import com.sgb.kjwl.di.transport.DaggerTransportFragComponent;
import com.sgb.kjwl.di.transport.TransportFragModule;
import com.sgb.kjwl.model.entity.transport.CarTypeAndCarLength;
import com.sgb.kjwl.model.entity.transport.CheckStateEntity;
import com.sgb.kjwl.model.entity.transport.GoodsHallFilterEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.GoodsSourceSearchEvent;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.transport.GoodsInfoJoinQuotedActivity3;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.FreightPrjDetailActivity;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.GeneralPrjDetailActivity;
import com.sgb.kjwl.view.ui.adapter.home.GoodsInfoAdapter;
import com.sgb.kjwl.view.widget.GoodsTypePopWindow3;
import com.sgb.kjwl.view.widget.LoadTimePopWindow;
import com.swgk.core.dialog.RoundDialog;
import com.sgb.kjwl.view.widget.SetWeightAndVolumeWindow;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.transport.GoodsInfofrgModel3;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import static com.sgb.kjwl.view.widget.GoodsMoreFilterPopWindow.DEFAULT_GOODS_TYPE;


public class GoodsListFragment extends AppFragment {

    public static final String GOODS_TYPE = "goods_type";
    public static final String DATA_TYPE = "websiteType";
    public static final String DATA_NO = "websiteNo";
    private static final String FLAG_FILTER = "flag_filter";
    private static final String PATTERN = "pattern";
    private static final String IS_SHOW_MORE_FILTER = "IS_SHOW_MORE_FILTER";
    private static final String CAN_REFRESH = "CAN_REFRESH";
    private static final int SEND_ADDRESS_SELECTING = 0;
    private static final int SEND_ADDRESS_SELECTED = 1;
    private static final int DEST_ADDRESS_SELECTING = 2;
    private static final int DEST_ADDRESS_SELECTED = 3;
    private static final int LOAD_TIME_SELECTING = 4;
    private static final int LOAD_TIME_SELECTED = 5;
    private static final int LOAD_TIME_UNSELECTED = 9;
    private static final int DEST_ADDRESS_UNSELECTED = 10;
    private static final int TRANSPORT_WEIGHT_SELECTING = 6;
    private static final int TRANSPORT_WEIGHT_SELECTED = 7;
    private static final int TRANSPORT_WEIGHT_UNSELECT = 8;

    private String goodsTypeNo = DEFAULT_GOODS_TYPE;
    private String websiteNo;
    private String websiteType;
    private Map<String, List<CarTypeAndCarLength>> allCarTypeAndCarLengthMap = new HashMap<>();
    private ThreeLevelAreaWindow sendGoodsLocationPopWindow3;
    private ThreeLevelAreaWindow destinationPopWindow;
    private SetWeightAndVolumeWindow weightAndVolumeWindow;
    private GoodsTypePopWindow3 goodsTypePopWindow;
    private LoadTimePopWindow loadTimePopWindow;
    //Fragment的View加载完毕的标记
    private boolean isViewCreated;
    //Fragment对用户可见的标记
    private boolean isUIVisible;
    private int page = 1;
    private boolean isLoadMore = false;
    private boolean isFirstLoadData = true;
    private int position = -1;

    private List<GoodsInfoTypeEntity3> goodsTypeData;
    private List<GoodsInfoTypeEntity3> carsTypeData;
    private List<GoodsInfoTypeEntity3> carsLengthData;

    public LatLng currentLatLng = new LatLng(NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "")),
            NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "")));

    // 一级联动数据
    public List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    public List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    public List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private int LOCATION_TYPE = -1;//0发货地，1目的地
    private boolean isFilterVisible = true;

    @Inject
    GoodsInfofrgModel3 goodsInfoModel3;
    private FragmentGoodsListBinding binding;
    private GoodsInfoAdapter goodsInfoAdapter;
    private String searchText;
    private int pattern = 0;
    private boolean isShowMoreFilter;
    private boolean canRefresh = true;

    public GoodsListFragment() {
    }


    public static GoodsListFragment newInstance(String goodsType, int pattern, boolean filterData, boolean isShowMoreFilter, boolean canRefresh) {
        GoodsListFragment fragment = new GoodsListFragment();
        Bundle args = new Bundle();
        args.putString(GOODS_TYPE, goodsType);
        args.putBoolean(FLAG_FILTER, filterData);
        args.putInt(PATTERN, pattern);
        args.putBoolean(IS_SHOW_MORE_FILTER, isShowMoreFilter);
        args.putBoolean(CAN_REFRESH, canRefresh);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 用户前台主页--物流需求列表（自营）
     *
     * @param websiteType 主页身份（个人、企业、团队）
     * @param no          身份no
     * @return
     */
    public static GoodsListFragment newInstance(String websiteType, String no) {
        GoodsListFragment fragment = new GoodsListFragment();
        Bundle args = new Bundle();
        args.putString(GOODS_TYPE, DEFAULT_GOODS_TYPE);
        args.putInt(PATTERN, 3);
        args.putString(DATA_TYPE, websiteType);
        args.putString(DATA_NO, no);
        args.putBoolean(FLAG_FILTER, true);
        args.putBoolean(IS_SHOW_MORE_FILTER, false);
        args.putBoolean(CAN_REFRESH, true);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            goodsTypeNo = getArguments().getString(GOODS_TYPE);
            websiteType = getArguments().getString(DATA_TYPE);
            websiteNo = getArguments().getString(DATA_NO);
            goodsInfoModel3.websiteNo = websiteType;
            goodsInfoModel3.websiteType = websiteType;
            isFilterVisible = getArguments().getBoolean(FLAG_FILTER, true);
            isShowMoreFilter = getArguments().getBoolean(IS_SHOW_MORE_FILTER, false);
            canRefresh = getArguments().getBoolean(CAN_REFRESH, true);
            pattern = getArguments().getInt(PATTERN, 0);
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerTransportFragComponent.builder()
                .appComponent(appComponent)
                .transportFragModule(new TransportFragModule(this))
                .build()
                .inject(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_goods_list, container, false);
        return binding.getRoot();
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        isViewCreated = true;
//        binding.selectLayout.setVisibility(isFilterVisible ? View.VISIBLE : View.GONE);
        binding.transportWeightLayout.setVisibility(isFilterVisible && pattern != 3 ? View.VISIBLE : View.GONE);
        binding.selectLayout.setVisibility(pattern != 3 && isFilterVisible ? View.VISIBLE : View.GONE);
        binding.loadTimeLayout.setVisibility(isFilterVisible ? View.VISIBLE : View.GONE);
        binding.goodsMoreLayout.setVisibility(isFilterVisible && isShowMoreFilter ? View.VISIBLE : View.INVISIBLE);
        initNeedVideoParams();
        if (!isFilterVisible) {
            binding.emptyView.setVisibility(View.VISIBLE);
            binding.goodsList.setVisibility(View.GONE);
        } else {
            refreshContentData(goodsTypeNo, pattern);
        }
    }

    private void initNeedVideoParams() {
        if (!TextUtils.isEmpty(websiteNo)) {
            goodsInfoModel3.filterEntity.get().setNeedVideo("0");
        } else {
            goodsInfoModel3.filterEntity.get().setNeedVideo("1");
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_goods_layout:
//                setUpLayout.upLayput();
                LOCATION_TYPE = 0;
                if (null != addressEntityList && addressEntityList.size() > 0) {
                    showSendPopWindow();
                } else {
//                    goodsInfoModel3.getAddressModel();
                }
                setViewStateByState(SEND_ADDRESS_SELECTING);
                break;
            case R.id.purpose_goods_layout:
                LOCATION_TYPE = 1;
                if (null != addressEntityList && addressEntityList.size() > 0) {
                    showDestinationPopWindow();
                } else {
//                    goodsInfoModel3.getAddressModel();
                }
                setViewStateByState(DEST_ADDRESS_SELECTING);
                break;
            case R.id.goods_more_layout:
                showMoreFilterPopWindow();
                break;

            case R.id.transport_weight_layout:
                showWeightAndVolumeWindow();
                break;
            case R.id.load_time_layout:
                showPopup(loadTimePopWindow);
                setViewStateByState(LOAD_TIME_SELECTING);
                break;
//            case R.id.push_accept:
//                break;
            case R.id.join_price:
                GoodsInfoJoinQuotedActivity3.start(getActivity());
                break;
            case R.id.message_num_layout:
                //消息
                // messagePopWindow.showPopwindowRight(binding.messageNumLayout);
                break;
//            case R.id.source_business:
//                GoodsInfoOrderSuccessActivity3.start(getActivity());
//                break;
        }
    }


    private void refreshData() {
        page = 1;
        isLoadMore = false;
        getFilterData(goodsTypeNo, pattern);
    }

    private void initView() {
        binding.sendGoodsLayout.setOnClickListener(this);
        binding.purposeGoodsLayout.setOnClickListener(this);
        binding.transportWeightLayout.setOnClickListener(this);
        binding.loadTimeLayout.setOnClickListener(this);
        binding.goodsMoreLayout.setOnClickListener(this);
        if (goodsInfoAdapter == null) {
            if (pattern == 3) {
                goodsInfoAdapter = new GoodsInfoAdapter(getActivity(), new ArrayList<>(), true);
            } else {
                goodsInfoAdapter = new GoodsInfoAdapter(getActivity(), new ArrayList<>());
                if(pattern==0){
                    goodsInfoAdapter.setPageName("7");
                }else{
                    goodsInfoAdapter.setPageName("8");
                }
            }
        }
        binding.goodsListRefreshLayout.setEnableLoadMore(true);
        if (pattern == 3) {
            binding.goodsListRefreshLayout.setEnableRefresh(true);
        } else {
            binding.goodsListRefreshLayout.setEnableRefresh(false);
        }
        binding.goodsList.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.goodsList.setAdapter(goodsInfoAdapter);
        goodsInfoAdapter.bindToRecyclerView(binding.goodsList);
        goodsInfoAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (goodsInfoAdapter.isMultipleClick()) {
                return;
            }
            if (null != goodsInfoAdapter && goodsInfoAdapter.getData().size() > 0) {
                goodsInfoModel3.goodsSourceStatusCheck(goodsInfoAdapter.getData().get(position).getNo(), position);
            }
        });
        binding.goodsListRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                if (isFilterVisible) {
                    page = page + 1;
                    getFilterData(goodsTypeNo, pattern);
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshListView();
            }
        });


        //发货省份popWindow
        sendGoodsLocationPopWindow3 = new ThreeLevelAreaWindow(getActivity()) {
            @Override
            protected void resultContent(String name, String simpleName) {
                binding.tvSend.setText(simpleName);
            }
        };
        sendGoodsLocationPopWindow3.setBgView(binding.grayLayout);
        sendGoodsLocationPopWindow3.setAreaSingle();
        sendGoodsLocationPopWindow3.setCitySingle();
        sendGoodsLocationPopWindow3.setProvinceSingle();
        sendGoodsLocationPopWindow3.setShowSimpleName(true);
        sendGoodsLocationPopWindow3.setAllSingleSelect(true);
        sendGoodsLocationPopWindow3.setOnlyShowProAndCity(true);
        sendGoodsLocationPopWindow3.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object proId, Object cityId, Object areaId) {
                BaseAreaEntity pro = (BaseAreaEntity) proId;
                BaseAreaEntity city = (BaseAreaEntity) cityId;
                BaseAreaEntity area = (BaseAreaEntity) areaId;
                GoodsSourceLocationEntity entity = new GoodsSourceLocationEntity();
                entity.setProvinceName(pro.getName());
                entity.setProvinceNo(pro.getNo());
                entity.setCityNo(city.getNo());
                entity.setCityName(city.getName());
                if (area != null) {
                    entity.setAreaNo(area.getNo());

                }
                entity.setAreaName(area.getName());
                goodsInfoModel3.sendLocation.set(entity);
                refreshData();
            }
        });
        sendGoodsLocationPopWindow3.setOnDismissListener(() -> {
            setViewStateByState(SEND_ADDRESS_SELECTED);
        });


        //收货省份popWindow
        destinationPopWindow = new ThreeLevelAreaWindow(getActivity()) {
            @Override
            protected void resultContent(String name, String simpleName) {
                binding.tvDestination.setText(simpleName);
            }
        };
        destinationPopWindow.setBgView(binding.grayLayout);
        destinationPopWindow.setAreaSingle();
        destinationPopWindow.setCitySingle();
        destinationPopWindow.setProvinceSingle();
        destinationPopWindow.setShowSimpleName(true);
        destinationPopWindow.setAllSingleSelect(true);
        destinationPopWindow.setOnlyShowProAndCity(true);
        destinationPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object proId, Object cityId, Object areaId) {
                BaseAreaEntity pro = (BaseAreaEntity) proId;
                BaseAreaEntity city = (BaseAreaEntity) cityId;
                BaseAreaEntity area = (BaseAreaEntity) areaId;
                GoodsSourceLocationEntity entity = new GoodsSourceLocationEntity();

                entity.setProvinceNo(pro.getNo());
                entity.setCityNo(city.getNo());
                if (area != null) {
                    entity.setAreaNo(area.getNo());
                }
                binding.tvDestination.setText(entity.getSimpleName());
                goodsInfoModel3.purposeLocation.set(entity);
                refreshData();
            }
        });
        destinationPopWindow.setOnDismissListener(() -> {
            boolean unSetDestAddress = "目的地".equals(binding.tvDestination.getText());
            if (unSetDestAddress) {
                setViewStateByState(DEST_ADDRESS_UNSELECTED);
            } else {
                setViewStateByState(DEST_ADDRESS_SELECTED);
            }
        });


        //货物类型
        goodsTypePopWindow = new GoodsTypePopWindow3(getActivity());
        goodsTypePopWindow.setBgView(binding.grayLayout);
        goodsTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) type;
                goodsInfoModel3.sourceType.set(entity);
                position = (int) key2;
                refreshData();
                LogUtil.v("goodsInfo", "货物类型=" + entity.getName());
            }
        });
        initLoadTimePopWindow();
        initWeightAndVolumeWindow();
    }

    private void getFilterData(String goodsTypeNo, int pattern) {
        initNeedVideoParams();
        goodsInfoModel3.getGoodsList(getContext(), page, goodsTypeNo, pattern, websiteType, websiteNo);
    }

    private void initWeightAndVolumeWindow() {
        weightAndVolumeWindow = new SetWeightAndVolumeWindow(getActivity(), (weightMin, weightMax, volumeMin, volumeMax) -> {
            goodsInfoModel3.filterEntity.get().setMaxWeight(String.valueOf(weightMax));
            goodsInfoModel3.filterEntity.get().setMinWeight(String.valueOf(weightMin));
            goodsInfoModel3.filterEntity.get().setMaxVolume(volumeMax);
            goodsInfoModel3.filterEntity.get().setVolume(volumeMin);
            refreshData();
        });
        weightAndVolumeWindow.setBgView(binding.grayLayout);
        weightAndVolumeWindow.setOnDismissListener(() -> {
            if (weightAndVolumeWindow.isUnSetWeightAndVolume()) {
                setViewStateByState(TRANSPORT_WEIGHT_UNSELECT);
            } else {
                setViewStateByState(TRANSPORT_WEIGHT_SELECTED);
                binding.transportWeight.setText(weightAndVolumeWindow.getWeightAndVolumeStr());
            }
        });
    }

    private void initLoadTimePopWindow() {
        loadTimePopWindow = new LoadTimePopWindow(getActivity());
        loadTimePopWindow.setBgView(binding.grayLayout);
        loadTimePopWindow.setOnDismissListener(() -> binding.loadTimeIv.setSelected(false));
        loadTimePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                GoodsInfoTypeEntity3 infoTypeEntity = (GoodsInfoTypeEntity3) key1;
                if (infoTypeEntity.getName().equals("明天以后")) {
                    goodsInfoModel3.filterEntity.get().setShipmentTime(infoTypeEntity.getNo());
                    goodsInfoModel3.filterEntity.get().setShipmentEndTime("");
                } else {
                    goodsInfoModel3.filterEntity.get().setShipmentTime("");
                    goodsInfoModel3.filterEntity.get().setShipmentEndTime(infoTypeEntity.getNo());
                }
                refreshData();
            }
        });
        loadTimePopWindow.setOnDismissListener(() -> {
            if (loadTimePopWindow.isSetLoadTime()) {
                setViewStateByState(LOAD_TIME_SELECTED);
                binding.loadTime.setText(loadTimePopWindow.getLoadTimeStr());
            } else {
                setViewStateByState(LOAD_TIME_UNSELECTED);
            }
        });
    }


    public void refreshContentData(String goodsTypeNo, int pattern) {
        if (!goodsTypeISChanged(goodsTypeNo)) {
            return;
        }
        finishRefreshOrLoadMore();
        resetFilterDataWhenGoodsTypeChanged(goodsTypeNo, pattern);
        getFilterData(goodsTypeNo, pattern);
        //只有展示筛选功能，才拉取筛选数据
        if (isFilterVisible) {
            if (!isInitAddressData()) {
                goodsInfoModel3.getAddressModel();
            }
        }
    }

    public boolean goodsTypeISChanged(String goodsTypeNo) {
        if (isFirstLoadData) {
            isFirstLoadData = false;
            return true;
        }
        return !this.goodsTypeNo.equals(goodsTypeNo);
    }

    private void resetFilterDataWhenGoodsTypeChanged(String goodsTypeNo, int pattern) {
        page = 1;
        isLoadMore = false;
        this.goodsTypeNo = goodsTypeNo;
        this.pattern = pattern;
        goodsInfoModel3.filterEntity.get().setCarType(null);
        goodsInfoModel3.filterEntity.get().setLengthType(null);

        //切换货物类型首页在这里不清除最大最小值，货运大厅要清除
        if (isFilterVisible && isShowMoreFilter) {
            goodsInfoModel3.filterEntity.get().setMaxWeight(null);
            goodsInfoModel3.filterEntity.get().setMinWeight(null);
            goodsInfoModel3.filterEntity.get().setShipmentTime("");
            goodsInfoModel3.filterEntity.get().setShipmentEndTime("");
        }

    }

    private boolean isInitAddressData() {
        return null != addressEntityList && addressEntityList.size() > 0;
    }


    //加载货物列表
    public void refreshGoodsInfoList(List<GoodsInfoEntity> list, boolean isMore) {
        if (isLoadMore) {
            binding.goodsListRefreshLayout.finishLoadMore();
            if (list.size() > 0) {
                goodsInfoAdapter.addData(list);
            } else {
                binding.goodsListRefreshLayout.finishLoadMoreWithNoMoreData();
            }
            binding.goodsList.setVisibility(View.VISIBLE);
        } else {
            binding.goodsListRefreshLayout.finishRefresh();
            if (list.size() > 0) {
                binding.goodsList.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                goodsInfoAdapter.setDatas(list);
                if (list.size() < 10) {
                    binding.goodsListRefreshLayout.finishLoadMoreWithNoMoreData();
                }
            } else {
                goodsInfoAdapter.setDatas(null);
                binding.goodsList.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
        binding.goodsListRefreshLayout.setNoMoreData(isMore);

    }


    //获取货物类型后更新数据
    public void getGoodsTypeData(List<GoodsInfoTypeEntity3> list) {
        if (null != list && list.size() > 0) {
            goodsTypeData = list;
//            showGoodsTypePopWindow();
        } else {
            MToast.showToast(getActivity(), "数据未加载");
        }
    }


    //获取车型
    public void getCarsTypeData(List<GoodsInfoTypeEntity3> list) {
        if (null != list && list.size() > 0) {
            carsTypeData = list;
        } else {
            MToast.showToast(getActivity(), "数据未加载");
        }
    }

    //获取车长
    public void getCarsLengthData(List<GoodsInfoTypeEntity3> list) {
        if (null != list && list.size() > 0) {
            carsLengthData = list;
        } else {
            MToast.showToast(getActivity(), "数据未加载");
        }
    }

    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        addressEntityList = datas;
        Log.v("public==source", datas.size() + "");
        initProvinceCityAreaData();
    }


    private void showSendPopWindow() {
        sendGoodsLocationPopWindow3.setData(addressEntityList, true);
        showPopup(sendGoodsLocationPopWindow3);
    }

    private void showDestinationPopWindow() {
        destinationPopWindow.setData(addressEntityList, true);
        showPopup(destinationPopWindow);
    }

    private void showWeightAndVolumeWindow() {
        showPopup(weightAndVolumeWindow);
        setViewStateByState(TRANSPORT_WEIGHT_SELECTING);
    }


    private void showGoodsTypePopWindow() {
        goodsTypePopWindow.showPopwindow(binding.sendGoodsLayout, 0, 0);
        goodsTypePopWindow.setData(goodsTypeData, position);
    }

    private void showMoreFilterPopWindow() {
        if (getActivity() instanceof MainActivity) {
            EventBus.getDefault().post(new GoodsSourceSearchEvent(EventConstant.EVENT_FILTER_OPEN, pattern, goodsTypeNo));
        }
    }

    /**
     * 展示选择弹窗
     */
    public void showPopup(BasePopWindow pop) {
        if (getActivity() instanceof MainActivity) {
            EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_LOGISTICS_WINDOW_TOP));
            new Handler().postDelayed(() -> pop.showPopwindow(binding.selectLayout, 0, 0), 300);
        } else {
            pop.showPopwindow(binding.selectLayout, 0, 0);
        }
    }


    private void setViewStateByState(int state) {
        switch (state) {
            case SEND_ADDRESS_SELECTING:
                binding.tvSend.setSelected(false);
                binding.sendGoodsIv.setSelected(true);
                binding.sendGoodsIv.setImageDrawable(getResources().getDrawable(R.mipmap.ic_up_arrow_n));
                binding.sendGoodsLayout.setBackground(getResources().getDrawable(R.drawable.circle_gray_bkg));
                break;
            case SEND_ADDRESS_SELECTED:
                binding.tvSend.setSelected(true);
                binding.sendGoodsIv.setSelected(false);
                binding.sendGoodsIv.setImageDrawable(getResources().getDrawable(R.mipmap.ic_down_arrow));
                binding.sendGoodsLayout.setBackground(getResources().getDrawable(R.drawable.shape_theme_coner));
                break;
            case DEST_ADDRESS_SELECTING:
                binding.tvDestination.setSelected(false);
                binding.purposeGoodsIv.setSelected(true);
                binding.purposeGoodsIv.setImageDrawable(getResources().getDrawable(R.mipmap.ic_up_arrow_n));
                binding.purposeGoodsLayout.setBackground(getResources().getDrawable(R.drawable.circle_gray_bkg));
                break;
            case DEST_ADDRESS_SELECTED:
                binding.tvDestination.setSelected(true);
                binding.purposeGoodsIv.setSelected(false);
                binding.purposeGoodsIv.setImageDrawable(getResources().getDrawable(R.mipmap.ic_down_arrow));
                binding.purposeGoodsLayout.setBackground(getResources().getDrawable(R.drawable.shape_theme_coner));
                break;
            case DEST_ADDRESS_UNSELECTED:
                binding.tvDestination.setSelected(false);
                binding.purposeGoodsIv.setSelected(false);
                binding.purposeGoodsIv.setImageDrawable(getResources().getDrawable(R.mipmap.ic_down_arrow_n));
                binding.purposeGoodsLayout.setBackground(getResources().getDrawable(R.drawable.circle_gray_bkg));
                break;
            case LOAD_TIME_SELECTING:
                binding.loadTime.setSelected(false);
                binding.loadTimeIv.setSelected(true);
                binding.loadTimeIv.setImageDrawable(getResources().getDrawable(R.mipmap.ic_up_arrow_n));
                binding.loadTimeLayout.setBackground(getResources().getDrawable(R.drawable.circle_gray_bkg));
                break;
            case LOAD_TIME_SELECTED:
                binding.loadTime.setSelected(true);
                binding.loadTimeIv.setSelected(false);
                binding.loadTimeIv.setImageDrawable(getResources().getDrawable(R.mipmap.ic_down_arrow));
                binding.loadTimeLayout.setBackground(getResources().getDrawable(R.drawable.shape_theme_coner));
                break;
            case LOAD_TIME_UNSELECTED:
                binding.loadTime.setSelected(false);
                binding.loadTimeIv.setSelected(false);
                binding.loadTimeIv.setImageDrawable(getResources().getDrawable(R.mipmap.ic_down_arrow_n));
                binding.loadTimeLayout.setBackground(getResources().getDrawable(R.drawable.circle_gray_bkg));
                break;
            case TRANSPORT_WEIGHT_SELECTING:
                binding.transportWeight.setSelected(false);
                binding.transportWeightIv.setSelected(true);
                binding.transportWeightIv.setImageDrawable(getResources().getDrawable(R.mipmap.ic_up_arrow_n));
                binding.transportWeightLayout.setBackground(getResources().getDrawable(R.drawable.circle_gray_bkg));
                break;
            case TRANSPORT_WEIGHT_SELECTED:
                binding.transportWeight.setSelected(true);
                binding.transportWeightIv.setSelected(false);
                binding.transportWeightIv.setImageDrawable(getResources().getDrawable(R.mipmap.ic_down_arrow));
                binding.transportWeightLayout.setBackground(getResources().getDrawable(R.drawable.shape_theme_coner));
                break;
            case TRANSPORT_WEIGHT_UNSELECT:
                binding.transportWeight.setSelected(false);
                binding.transportWeight.setText("运量");
                binding.transportWeightIv.setSelected(false);
                binding.transportWeightIv.setImageDrawable(getResources().getDrawable(R.mipmap.ic_down_arrow_n));
                binding.transportWeightLayout.setBackground(getResources().getDrawable(R.drawable.circle_gray_bkg));
                break;
        }
    }

    private void initProvinceCityAreaData() {
        String proName = "不限", cityName = "不限", areaName = "不限";
        binding.tvSend.setText("全国");
        setViewStateByState(SEND_ADDRESS_SELECTED);
        sendGoodsLocationPopWindow3.setDataAndPosition(addressEntityList, proName, cityName, areaName, true, true);
//        BaseAreaEntity[] entities = sendGoodsLocationPopWindow3.findCode(proName, cityName, areaName);
//        if (entities.length > 0) {
//            goodsInfoModel3.sendLocation.get().setProvinceNo(entities[0].getNo());
//            goodsInfoModel3.sendLocation.get().setProvinceName(entities[0].getSimpleName());
//            goodsInfoModel3.sendLocation.get().setCityNo(entities[1].getNo());
//            goodsInfoModel3.sendLocation.get().setCityName(entities[1].getSimpleName());
//        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_ORDER_FINISH) {
            if (isFilterVisible) {
                page = 1;
                getFilterData(goodsTypeNo, pattern);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_LOGISTICS_REFRESH) {
            refreshListView();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(GoodsSourceSearchEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_FILTER_SURE) {
            if (event.getFilterEntity() != null && event.getPattern() == pattern) {
                GoodsHallFilterEntity filterEntity = (GoodsHallFilterEntity) event.getFilterEntity();
                goodsInfoModel3.filterEntity.get().setCarType(filterEntity.getCarType());
                goodsInfoModel3.filterEntity.get().setLengthType(filterEntity.getLengthType());
                goodsTypeNo = event.getNo();
                refreshData();
            }
        }
    }

    private void refreshListView() {
        isLoadMore = false;
        if (isFilterVisible) {
            page = 1;
            getFilterData(goodsTypeNo, pattern);
        }

    }

    public void checkGoodsState(int position, CheckStateEntity stateEntity) {
        if (stateEntity.goodsIsGone()) {
            new RoundDialog.Builder(getActivity())
                    .title("提示")
                    .content("该货源不存在，请选择其他货源接单")
                    .singleBtn(true)
                    .confirm("知道了")
                    .confirmCallback(v -> {
                        goodsInfoAdapter.getData().remove(position);
                        goodsInfoAdapter.notifyDataSetChanged();
                    })
                    .show();
        } else if (stateEntity.goodsIsReceipted()) {
            new RoundDialog.Builder(getActivity())
                    .title("提示")
                    .content("该货源已被接单，请选择其他货源接单")
                    .singleBtn(true)
                    .confirm("知道了")
                    .confirmCallback(v -> {
                        goodsInfoAdapter.getData().remove(position);
                        goodsInfoAdapter.notifyDataSetChanged();
                    })
                    .show();
        } else {
            if (null != goodsInfoAdapter && goodsInfoAdapter.getData().size() > 0) {
                if (goodsInfoAdapter.getData().get(position) != null) {
                    if (goodsInfoAdapter.getData().get(position).getPattern() == 1) {
                        FreightPrjDetailActivity.start(getActivity(), goodsInfoAdapter.getData().get(position).getNo(), false, false);
                    } else {
                        GeneralPrjDetailActivity.start(getActivity(), goodsInfoAdapter.getData().get(position).getNo(), goodsInfoAdapter.getData().get(position).getPattern(), false);
                    }
                }
            }
        }
    }


    public boolean isContainCarTypeAndCarLengthByGoodsNo(String goodsNo) {
        if (goodsNo == null) {
            return false;
        }
        return allCarTypeAndCarLengthMap.keySet().contains(goodsNo);
    }

    public void finishRefreshOrLoadMore() {
        if (isLoadMore) {
            binding.goodsListRefreshLayout.finishLoadMore();
        } else {
            binding.goodsListRefreshLayout.finishRefresh();
        }
    }


}